<template>
  <div class="avatar-wrap">
    <div class="avatar-container" @click="openEditHeaderModal">
      <nut-avatar class="avatar" size="large">
        <img v-if="userProfile.headImg" :src="userProfile.headImg" />
        <img v-else src="https://img12.360buyimg.com/imagetools/jfs/t1/143702/31/16654/116794/5fc6f541Edebf8a57/4138097748889987.png" />
      </nut-avatar>
      <div class="avatar-edit-icon">
        <Edit size="16" />
      </div>
    </div>
    <div class="member-detail">
      <p class="nickname">
        <span v-if="userProfile.distributorName || userProfile.nickName">
          用户名: {{ userProfile.nickName || userProfile.distributorName }}
        </span>
        <nut-button v-else shape="square" size="small" type="default" @click="goLogin">去登录</nut-button>
      </p>
      <p class="phone" v-if="userProfile.phone">手机号: {{ userProfile.phone }}</p>
    </div>
  </div>
  <nut-cell-group class="feature-list">
    <nut-cell title="修改密码" is-link @click="openChangePasswordModal" />
    <nut-cell title="退出登录" is-link @click="handleLogout" />
  </nut-cell-group>
  <nut-popup v-model:visible="showChangePasswordModal" position="center" round :style="{ padding: '24px', width: '80%' }">
    <div class="change-password-modal">
      <h3 class="modal-title">修改密码</h3>
      <nut-form ref="changePasswordFormRef" :model-value="changePasswordForm">
        <nut-form-item label="旧密码" required prop="oldPassword" :rules="[{ required: true, message: '请输入旧密码' }]">
          <nut-input v-model="changePasswordForm.oldPassword" placeholder="请输入旧密码" type="password" clearable />
        </nut-form-item>
        <nut-form-item label="新密码" required prop="newPassword" :rules="[{ required: true, message: '请输入新密码' }]">
          <nut-input v-model="changePasswordForm.newPassword" placeholder="请输入新密码" type="password" clearable />
        </nut-form-item>
      </nut-form>
      <div class="modal-actions">
        <nut-button class="modal-btn" plain type="default" @click="closeChangePasswordModal">取消</nut-button>
        <nut-button class="modal-btn" type="primary" :loading="changePasswordLoading" @click="handleChangePassword"> 确认 </nut-button>
      </div>
    </div>
  </nut-popup>
  <nut-popup v-model:visible="showEditHeaderModal" position="center" round :style="{ padding: '24px', width: '80%' }">
    <div class="edit-header-modal">
      <h3 class="modal-title">编辑头像和昵称</h3>
      <div class="avatar-upload-section">
        <nut-avatar class="preview-avatar" size="large">
          <img v-if="editHeaderForm.headImg" :src="editHeaderForm.headImg" />
          <img v-else-if="userProfile.headImg" :src="userProfile.headImg" />
          <img v-else src="https://img12.360buyimg.com/imagetools/jfs/t1/143702/31/16654/116794/5fc6f541Edebf8a57/4138097748889987.png" />
        </nut-avatar>
        <nut-button type="primary" size="small" :loading="uploading" @click="handleImageUpload">
          {{ uploading ? '上传中...' : '选择图片' }}
        </nut-button>
        <input ref="fileInputRef" type="file" accept="image/*" style="display: none" @change="handleFileChange" />
      </div>
      <nut-form ref="editHeaderFormRef" :model-value="editHeaderForm">
        <nut-form-item label="昵称" prop="nickName">
          <nut-input v-model="editHeaderForm.nickName" placeholder="请输入昵称" clearable />
        </nut-form-item>
      </nut-form>
      <div class="modal-actions">
        <nut-button class="modal-btn" plain type="default" @click="closeEditHeaderModal">取消</nut-button>
        <nut-button class="modal-btn" type="primary" :loading="updateHeaderLoading" @click="handleUpdateHeader"> 确认 </nut-button>
      </div>
    </div>
  </nut-popup>
</template>

<script setup lang="ts">
  import { computed, onActivated, onMounted, reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { showToast } from '@nutui/nutui';
  import { Edit } from '@nutui/icons-vue';
  import { uploadFile } from '@/api';

  const router = useRouter();
  const userStore = useUserStore();

  const userProfile = computed(() => ({
    distributorId: userStore.userInfo?.distributorId ?? '',
    distributorName: userStore.userInfo?.distributorName ?? '',
    phone: userStore.userInfo?.phone ?? '',
    headImg: userStore.userInfo?.headImg ?? '',
    nickName: userStore.userInfo?.nickName ?? '',
  }));

  const showId = ref(false);
  const showDistributorId = () => {
    showId.value = !showId.value;
  };

  const syncUserInfo = async () => {
    if (!userStore.isLoggedIn || userStore.userInfo) {
      return;
    }
    try {
      await userStore.getUserInfo();
    } catch (error) {
      console.error('获取用户信息失败', error);
      await userStore.logout();
    }
  };

  onMounted(() => {
    void syncUserInfo();
  });

  onActivated(() => {
    void syncUserInfo();
  });

  const showChangePasswordModal = ref(false);
  const changePasswordFormRef = ref<any>(null);
  const changePasswordForm = reactive({
    oldPassword: '',
    newPassword: '',
  });
  const changePasswordLoading = ref(false);

  const resetChangePasswordForm = () => {
    changePasswordForm.oldPassword = '';
    changePasswordForm.newPassword = '';
    const formInstance = changePasswordFormRef.value;
    if (formInstance && typeof formInstance.reset === 'function') {
      formInstance.reset();
    }
  };

  const openChangePasswordModal = () => {
    showChangePasswordModal.value = true;
  };

  const closeChangePasswordModal = () => {
    showChangePasswordModal.value = false;
    resetChangePasswordForm();
  };

  const handleChangePassword = () => {
    changePasswordFormRef.value?.validate().then(async ({ valid, errors }: any) => {
      if (!valid) {
        console.warn(errors);
        return;
      }
      try {
        changePasswordLoading.value = true;
        const res: any = await userStore.updatePassword({
          oldPassword: changePasswordForm.oldPassword,
          newPassword: changePasswordForm.newPassword,
        });
        if (res.data.code !== 200) throw new Error(res.data.msg);
        showToast.text(res.data.msg);
        closeChangePasswordModal();
      } catch (error: any) {
        console.error('修改密码失败', error);
        showToast.text(error?.message || '修改密码失败');
      } finally {
        changePasswordLoading.value = false;
      }
    });
  };

  const handleLogout = async () => {
    closeChangePasswordModal();
    await userStore.logout();
    router.replace('/login');
  };

  const goLogin = () => {
    router.push('/login');
  };

  // 编辑头像和昵称相关
  const showEditHeaderModal = ref(false);
  const editHeaderFormRef = ref<any>(null);
  const fileInputRef = ref<HTMLInputElement | null>(null);
  const uploading = ref(false);
  const updateHeaderLoading = ref(false);
  const editHeaderForm = reactive({
    headImg: '',
    nickName: '',
  });

  const openEditHeaderModal = () => {
    if (!userStore.isLoggedIn) {
      goLogin();
      return;
    }
    editHeaderForm.headImg = userProfile.value.headImg;
    editHeaderForm.nickName = userProfile.value.nickName || userProfile.value.distributorName || '';
    showEditHeaderModal.value = true;
  };

  const closeEditHeaderModal = () => {
    showEditHeaderModal.value = false;
    editHeaderForm.headImg = '';
    editHeaderForm.nickName = '';
  };

  const handleImageUpload = () => {
    fileInputRef.value?.click();
  };

  const handleFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      showToast.text('请选择图片文件');
      return;
    }

    // 验证文件大小（限制 5MB）
    if (file.size > 5 * 1024 * 1024) {
      showToast.text('图片大小不能超过 5MB');
      return;
    }

    try {
      uploading.value = true;
      const result = await uploadFile(file);
      if (result?.url) {
        editHeaderForm.headImg = result.url;
        showToast.text('图片上传成功');
      } else {
        showToast.text('图片上传失败');
      }
    } catch (error: any) {
      console.error('图片上传失败', error);
      showToast.text(error?.message || '图片上传失败');
    } finally {
      uploading.value = false;
      // 清空 input，以便可以重复选择同一文件
      if (target) {
        target.value = '';
      }
    }
  };

  const handleUpdateHeader = async () => {
    try {
      updateHeaderLoading.value = true;
      await userStore.updateUserHeader({
        headImg: editHeaderForm.headImg || null,
        nickName: editHeaderForm.nickName || null,
      });
      showToast.text('更新成功');
      closeEditHeaderModal();
    } catch (error: any) {
      console.error('更新头像昵称失败', error);
      showToast.text(error?.message || '更新失败');
    } finally {
      updateHeaderLoading.value = false;
    }
  };
</script>

<style lang="scss">
  .avatar-wrap {
    display: flex;
    align-items: center;
    margin: 10px 40px;

    .avatar-container {
      position: relative;
      cursor: pointer;

      .avatar-edit-icon {
        position: absolute;
        bottom: 0;
        right: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        background: #fff;
        border-radius: 50%;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }
    }

    .member-detail {
      margin-left: 20px;

      .info {
        display: flex;
        align-items: center;
        font-size: 26px;
        color: #666;
        cursor: pointer;

        .id-label {
          font-weight: bold;
          margin-right: 4px;
        }

        .id-text {
          margin-left: 4px;
        }

        .id-hint {
          margin-left: 8px;
          font-size: 22px;
          color: #999;
        }
      }

      .nickname {
        margin-top: 12px;
        font-size: 32px;
        font-weight: bold;

        .nut-button {
          margin-left: 10px;
        }
      }

      .phone {
        margin-top: 12px;
        font-size: 26px;
      }
    }
  }

  .feature-list {
    margin: 20px 0;
  }

  .change-password-modal,
  .edit-header-modal {
    display: flex;
    flex-direction: column;

    .modal-title {
      margin: 0 0 12px;
      font-size: 32px;
      text-align: center;
    }

    .avatar-upload-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 16px;

      .preview-avatar {
        margin-bottom: 12px;
      }
    }

    .modal-actions {
      display: flex;
      justify-content: space-between;
      margin-top: 16px;

      .modal-btn {
        flex: 1;

        &:first-child {
          margin-right: 16px;
        }
      }
    }
  }
</style>
